<template>
  <div class="device-push">
    <div class="card-container" style="padding-bottom: 0px">
      <Row>
        <Col v-bind="{ md: 24, lg: 18 }">
          <Form
            :model="queryParams"
            ref="queryForm"
            :label-col="{ style: { width: '100px' } }"
            :wrapper-col="{ span: 24 }"
          >
            <Row :gutter="20">
              <Col :span="8">
                <FormItem label="所属项目" name="project">
                  <TreeSelect
                    v-model:value="queryParams.project"
                    :treeData="projectList"
                    :treeCheckable="true"
                    :maxTagCount="0"
                    :allowClear="true"
                    :fieldNames="{ value: 'id' }"
                    placeholder="请选择所属项目"
                    :maxTagPlaceholder="maxTag"
                  >
                    <template #title="{ label, type }">
                      <span style="color: #bababa" v-if="type == '1'">{{
                        label
                      }}</span>
                      <span v-else>{{ label }}</span>
                    </template>
                  </TreeSelect>
                </FormItem>
              </Col>
              <Col :span="8">
                <!--   @change="handleType" -->
                <FormItem label="设备类型" name="deviceType">
                  <Select
                    v-model:value="queryParams.deviceType"
                    placeholder="请选择设备类型"
                    @change="changeDeviceType"
                  >
                    <SelectOption
                      v-if="deviceTypeList.length != 1"
                      :value="allChange()"
                      >全部</SelectOption
                    >
                    <SelectOption
                      v-for="(item, index) in deviceTypeList"
                      :key="index"
                      :value="item.value"
                      >{{ item.label }}</SelectOption
                    >
                  </Select>
                </FormItem></Col
              >
              <Col :span="8">
                <FormItem label="设备型号" name="modelIdList">
                  <Select
                    mode="multiple"
                    allowClear
                    :maxTagCount="0"
                    :maxTagPlaceholder="maxModalTag"
                    v-model:value="queryParams.modelIdList"
                    placeholder="请选择设备型号"
                  >
                    <SelectOption
                      v-for="item in modalList"
                      :key="item.modelId"
                      :value="item.modelId"
                      >{{ item.model }}</SelectOption
                    >
                  </Select>
                </FormItem></Col
              >
              <Col :span="8">
                <FormItem label="设备序列号" name="deviceCode">
                  <Input
                    v-model:value="queryParams.deviceCode"
                    placeholder="请输入设备序列号"
                    allowClear
                    @pressEnter="handleQuery"
                  /> </FormItem
              ></Col>
              <Col :span="8">
                <FormItem label="软件版本" name="version">
                  <FormItemRest>
                    <Space :size="8">
                      <Input
                        v-model:value="queryParams.version"
                        placeholder="请输入"
                        allowClear
                        @pressEnter="handleQuery"
                        :disabled="
                          page == 'softwareVersion' && row.appUpdateType == '2'
                        "
                      />
                      <Input
                        v-model:value="queryParams.versionCode"
                        placeholder="请输入"
                        allowClear
                        @pressEnter="handleQuery"
                        :disabled="
                          page == 'softwareVersion' && row.appUpdateType == '2'
                        "
                      />
                    </Space>
                  </FormItemRest> </FormItem
              ></Col>
              <Col :span="8">
                <FormItem label="固件版本" name="firmwareVersion">
                  <Input
                    v-model:value="queryParams.firmwareVersion"
                    placeholder="请输入固件版本"
                    allowClear
                    @pressEnter="handleQuery"
                  /> </FormItem
              ></Col>
            </Row>
          </Form>
        </Col>
        <Col v-bind="{ md: 24, lg: 6 }">
          <Flex justify="end">
            <Space>
              <b-button icon="search" @click="handleQuery"> 搜索 </b-button>
              <b-button icon="reset" @click="resetQuery"> 重置 </b-button>
            </Space>
          </Flex>
        </Col>
      </Row>
    </div>
    <Flex justify="end" class="my-2 h-[32px]">
      <Space v-show="!multiple">
        <b-button icon="reset" @click="handleAdd"> 加入推送列表 </b-button>
      </Space>
      <div class="shop">
        <ShoppingOutlined />
        <span class="num">{{ pushData.length }}</span>
      </div>
    </Flex>
    <Table
      ref="tableRef"
      row-key="deviceCode"
      :columns="columns"
      :data-source="tableData"
      :row-selection="rowSelection"
      :scroll="{ x: 500, y: 300 }"
      :pagination="{
        total: total,
        showTotal: (total) => `共${total}条`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '15', '30', '45'],
        current: queryParams.pageNum,
        pageSize: queryParams.pageSize,
      }"
      @change="onShowSizeChange"
    >
      <!-- <template #bodyCell="{ column, record }">
        <template
          v-if="column.dataIndex === 'operation' && record.onlineStatus == 1"
        >
          <b-button icon="data" type="link" @click="() => onHistoryData(record)"
            >实时数据</b-button
          >
        </template>
      </template> -->
    </Table>
  </div>
</template>

<script setup lang="ts">
import { PropType, computed, inject, onMounted, ref, watch } from 'vue';
import { ShoppingOutlined } from '@ant-design/icons-vue';
import {
  Button,
  Col,
  Flex,
  Form,
  FormItem,
  FormItemRest,
  Input,
  Pagination,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  type TableProps,
  TreeSelect,
  message,
} from 'ant-design-vue';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { columnWidth, listToEnum, listToOption } from '@/utils/utils';
import { getProjectData } from '@/api/config';
import { fetchDictsOfType } from '@/api/dict';
import { getModelInfoById, getTestProjectDeviceMapNew } from '@/api/push';

interface QueryParams {
  pageNum: number;
  pageSize: number;
  modelIdList: [];
  projectId: string | null;
  version: string | null;
  deviceCode: string | null;
  project: [];
  startVersion: number | null;
  endVersion: number | null;
  firmwareVersion: string | null;
  rangeModelIdList: [];
  onlineStatus: string;
  deviceType?: string;
  versionCode?: string;
  appUpdateType?: string;
}

interface TableRecord {
  deviceCode: string;
  deviceId: string;
  [key: string]: any;
}
const page = inject('page');

const props = defineProps({
  row: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({}),
  },
  deviceData: {
    type: Array as PropType<TableRecord[]>,
    default: () => [],
  },
});
console.log(props.row, 'rrrrowoww');

const emit = defineEmits(['pushData']);

watch(
  () => props.deviceData,
  (newValue: TableRecord[]) => {
    pushData.value = newValue;
    getProject();
  },
);

const queryParams = ref<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  modelIdList: [],
  projectId: null,
  version: null,
  deviceCode: null,
  project: [],
  startVersion: null,
  endVersion: null,
  firmwareVersion: null,
  rangeModelIdList: [],
  onlineStatus: '1',
});
const tableRef = ref();
const projectList = ref<any[]>([]);
const deviceTypeList = ref<any[]>([]);
const modalList = ref<any[]>([]);
const tableData = ref<TableRecord[]>([]);
const total = ref(0);
const selectedRow = ref<TableRecord[]>([]);
const multiple = ref(true);
const pushData = ref<TableRecord[]>([]);
const modelIds = ref<string[]>([]);
let projectDataAllNum = 0;
const sysDeviceModeEnum = ref<Record<string, any>>({});
const sysDeviceModeOptions = ref<Record<string, any>>([]);
onMounted(() => {
  fetchDictsOfType(['sys_device_mode']).then((res: any) => {
    const { sys_device_mode, sys_on_line_status } = res.data;
    sysDeviceModeOptions.value = listToOption(
      sys_device_mode,
      'dictLabel',
      'dictValue',
    );
    sysDeviceModeEnum.value = listToEnum(
      sys_device_mode,
      'dictValue',
      'dictLabel',
    );
  });
  console.log(sysDeviceModeEnum.value, 'sysDeviceModeEnum.value');
  getConfig();
});

const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectedRow.value.map((row) => row.deviceCode), // Extract deviceCode for selectedRowKeys
    onChange: (
      selectedRowKeys: (string | number)[],
      selectedRows: TableRecord[],
    ) => {
      handlePushSelection(selectedRowKeys as string[], selectedRows);
    },
    getCheckboxProps: (record: TableRecord) => ({
      deviceCode: record.deviceCode,
      disabled: false,
    }),
  };
});
const countProjectNodes = (tree: any) => {
  let count = 0;
  tree.forEach((node: any) => {
    if (node.children && node.children.length > 0) {
      count += countProjectNodes(node.children);
    } else {
      count++;
    }
  });
  return count;
};
const getConfig = async () => {
  const res = await getProjectData({ testStatus: '0' });
  if (res.code === 200) {
    projectList.value = res.data as any;
    projectList.value.forEach(processItem);
    projectDataAllNum = countProjectNodes(res.data);
    getData();
  }
};
const maxTag = (omittedValues: any) => {
  if (omittedValues.length == 1) {
    return omittedValues[0].label;
  } else if (omittedValues.length == projectDataAllNum) {
    return '全部';
  } else {
    return '多项目';
  }
};

const maxModalTag = (omittedValues: any) => {
  if (omittedValues.length == 1) {
    return omittedValues[0].label;
  } else if (omittedValues.length == modalList.value.length) {
    return '全部';
  } else {
    return '多设备';
  }
};
const processItem = (item: any) => {
  queryParams.value.project.push(item.id);
  if (item.children) {
    item.children.forEach(processItem);
  }
};

// const handleType = async (val: string) => {
//   const res = await getModelInfoById({
//     type: val,
//     modelIds: modelIds.value.join(','),
//   });
//   modalList.value = res.data as any;
// };

const formatDeviceType = (val: any) => {
  val = val ? val : [];
  let typeList = [];
  if (Array.isArray(val)) {
    sysDeviceModeOptions.value.filter((item) => {
      val.includes(item.value) && typeList.push(item);
    });
    return typeList;
  }
};

const formatModal = (val: any) => {
  let arr = modalList.value.filter((item) => {
    return item.modelId == val;
  });
  return arr[0]?.model;
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.projectIds = queryParams.value.project.join(',');
  getProject();
};

const resetQuery = () => {
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  queryParams.value.deviceCode = null;
  queryParams.value.project = [];
  queryParams.value.firmwareVersion = null;
  queryParams.value.versionCode = props.row.currentVersionCode;
  // if (props.row.appUpdateType === '2') {
  // queryParams.value.version = `${props.row.currentVersion}(${props.row.currentVersionCode})`;
  // } else {
  queryParams.value.version = props.row.currentVersion;
  // }
  queryParams.value.appUpdateType = props.row.appUpdateType;
  queryParams.value.modelIdList = props.row.modelIds;
  queryParams.value.rangeModelIdList = props.row.modelIds;
  queryParams.value.endVersion = Number(props.row.version);
  queryParams.value.onlineStatus = '1';
  if (deviceTypeList.value.length === 1) {
    queryParams.value.deviceType = deviceTypeList.value[0].value;
  } else {
    queryParams.value.deviceType = allChange();
  }
  projectList.value.forEach(processItem);

  handleQuery();
};
const allChange = () => {
  let _arr = deviceTypeList.value.map((item) => {
    return item.value;
  });
  return _arr.join(',');
};
const getData = async () => {
  deviceTypeList.value = props.row.deviceType
    ? formatDeviceType(props.row.deviceType.split(','))
    : [];
  if (props.row.deviceType.length === 1) {
    queryParams.value.deviceType = props.row.deviceType;
  } else {
    queryParams.value.deviceType = allChange();
  }
  const modelRes = await getModelInfoById({
    type: '',
    modelIds: props.row.modelIds.join(','),
  });
  modalList.value = modelRes.data;
  modelIds.value = props.row.modelIds;
  queryParams.value.version = props.row.currentVersion;
  // if (props.row.appUpdateType === '2') {
  //   queryParams.value.version = `${props.row.currentVersion}(${props.row.currentVersionCode})`;
  // }
  queryParams.value.endVersion = Number(props.row.version);
  queryParams.value.versionCode = props.row.currentVersionCode;
  queryParams.value.appUpdateType = props.row.appUpdateType;
  queryParams.value.modelIdList = props.row.modelIds;
  queryParams.value.rangeModelIdList = props.row.modelIds;
  getProject();
  // }
};
const onShowSizeChange = (info: number) => {
  const { current, pageSize } = info;
  queryParams.value.pageNum = current;
  queryParams.value.pageSize = pageSize;
  getProject();
};
const getProject = async () => {
  const res = await getTestProjectDeviceMapNew(queryParams.value);
  if (res.code === 200) {
    res.rows.forEach((item: TableRecord) => {
      item.isselect = false;
    });
    tableData.value = res.rows;
    for (let i = 0; i < pushData.value.length; i++) {
      for (let j = 0; j < tableData.value.length; j++) {
        if (
          pushData.value[i].deviceCode === tableData.value[j].deviceCode &&
          pushData.value[i].deviceId === tableData.value[j].deviceId
        ) {
          tableData.value.splice(j, 1);
        }
      }
    }
    total.value = res.total;
  }
};
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '所属项目',
    dataIndex: 'shortName',
    align: 'center',
    width: columnWidth('shortName', tableData.value, '所属项目'),
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    align: 'center',
    width: columnWidth('deviceCode', tableData.value, '所属项目'),
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    align: 'center',
    width: columnWidth('softwareVersion', tableData.value, '所属项目'),
    customRender({ text, record }) {
      return text + (record.versionCode ? `(${record.versionCode})` : '');
    },
  },
  {
    title: '固件版本',
    dataIndex: 'firmwareVersion',
    align: 'center',
    width: columnWidth('firmwareVersion', tableData.value, '所属项目'),
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    align: 'center',
    customRender({ text }) {
      return formatModal(text);
    },

    width: columnWidth('modelId', tableData.value, '所属项目'),
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    align: 'center',
    width: columnWidth('deviceType', tableData.value, '所属项目'),
    customRender({ text }) {
      return sysDeviceModeEnum.value[text as string];
    },
  },
  {
    title: '地址',
    dataIndex: 'address',
    align: 'center',
    width: columnWidth('address', tableData.value, '所属项目'),
  },
]);

const handlePushSelection = (keys: string[], rows: TableRecord[]) => {
  selectedRow.value = rows;
  multiple.value = !rows.length;
};

const handleAdd = () => {
  for (let i = 0; i < selectedRow.value.length; i++) {
    for (let j = 0; j < tableData.value.length; j++) {
      if (
        selectedRow.value[i].deviceCode === tableData.value[j].deviceCode &&
        selectedRow.value[i].deviceId === tableData.value[j].deviceId
      ) {
        tableData.value.splice(j, 1);
      }
    }
  }
  pushData.value.push(...selectedRow.value);
  if (rowSelection.value && rowSelection.value.onChange) {
    rowSelection.value.onChange([], []);
    selectedRow.value = [];
  }
  message.success('已加入推送列表');
  emit('pushData', pushData.value);
};

const changeDeviceType = async (value: any) => {
  const list = ['1', '2', '3'];
  const modelRes = await getModelInfoById({
    type: list.includes(value) ? value : '',
    modelIds: props.row.modelIds.join(','),
  });
  modalList.value = modelRes.data;
};
</script>

<style lang="scss" scoped>
.device-push {
  position: relative;

  .back {
    position: absolute;
    top: -35px;
    right: -5px;
    font-size: 16px;
    color: #fff;
    z-index: 10;
    cursor: pointer;
  }
}

.tab-box {
  margin-top: 10px;
  position: relative;

  .table-title {
    height: 36px;
    line-height: 36px;
    font-size: 16px;
    color: #fff;
  }

  .add-btn {
    position: absolute;
    right: 18px;
    top: 0px;
  }
}
:deep(.ant-table) {
  height: 40vh;
}
.shop {
  position: relative;
  font-size: 20px;
  margin-left: 20px;
  .num {
    position: absolute;
    right: -8px;
    top: 2px;
    font-size: 10px;
    background-color: #1890ff;
    border-radius: 50%;
    padding: 1px 4px;
  }
}
</style>
